# encoding: utf-8
# Author    : limusen
# Datetime  : 2023/8/11 15:25
# File      : base.py
# explain   : 文件说明

import base64
import json
import os
import ddddocr  # 验证码识别
from common.replace_source import replace_source
from common.replace_sink import replace_sink
from common.read_yaml import get_yml_data, revise_yml_data
from common.log import logger
from common.http_api import Api
from simple_settings import settings

root_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))


class Bases(Api):
    """ 基类 """
    path = os.path.join(root_dir + get_yml_data('config', 'all_param', 'path')['save_photos'])
    ocr = ddddocr.DdddOcr()  # 文件识别包

    def __init__(self):
        self.token_url = get_yml_data('config', 'all_param', 'urls')
        super().__init__(host=settings.api_host)

    def ReplaceSource(self, name=None):
        """
        用参数化的方式来选择配置文件。 %s %s
        :param host:
        :param name:
        :return:
        """
        if name:
            revise_yml_data('config', 'source', 'source', 'palayod', name, 'task_name')
        return replace_source(**get_yml_data('config', 'source', 'source')[0]['palayod'])

    def ReplaceSink(self, name=None):
        if name:
            revise_yml_data('config', 'sink', 'sink', 'palayod', name, 'task_name')
        return replace_sink(**get_yml_data('config', 'sink', 'sink')[0]['palayod'])

    def ProcessBase64(self, data, path=path):
        """
        处理图片文件转换成base64
        :param data: response的响应数据
        :param path: 存储图片的目标地址
        :return: 保存好图片到指定本地地址
        """
        try:
            revise_yml_data('sync', 'login', 'login_params', 'palayod', data['data']['codeId'],
                            'codeId')  # 读取yaml文件配置
            info_str = json.dumps(data['data']['img'])
            info_split = info_str.split('base64,')
            base_info = base64.b64decode(info_split[1])
            # 转存base64文件
            file = open(path, 'wb')
            file.write(base_info)
            file.close()
        except Exception as e:
            logger.error(e.__str__())
            return e.__str__()

    def ImageRecognition(self, path=path):
        """
        识别验证码方法
        :param path: 保存好的base64文件地址 地址配置在 all_param.path
        :return: 识别完成的验证码
        """
        try:
            with open(path, 'rb') as pf:
                img_bytes = pf.read()
                pf.close()

            result = Bases.ocr.classification(img_bytes)
            revise_yml_data('sync', 'login', 'login_params', 'palayod', result, 'code')  # 读取yaml文件配置
            logger.debug("获取验证码成功： %s" % result)
            return result

        except Exception as e:
            logger.error(e.__str__())
            return e.__str__()

    def GetCode(self):
        """
        请求验证码接口，拼接验证码code、codeid 登录
        :param host: 域名
        :return: 请求验证码参数
        """
        try:
            url = 'auth/captcha?_t=1692003021098'
            self.ProcessBase64(self.request('get', url).json())
            self.ImageRecognition()
            return get_yml_data('sync', 'login', 'login_params')[0]['palayod']
        except Exception as e:
            logger.error(e.__str__())
            return False


if __name__ == '__main__':
    res = Bases()
    print(res.GetCode())
    print(res.ReplaceSource())
    print(res.ReplaceSink())
